package com.levi.utils;

import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author shentong
 * @since 2022/3/29 10:39 PM
 * BeanList转换
 */
public class BeanConvertUtil {


    public static <T> List<T> listConvert(List<?> sources, Class<T> targetClass) {
        if (sources == null) {
            sources = Collections.emptyList();
        }
        //1.创建目标list
        List<T> targets = new ArrayList<>(sources.size());
        convert(sources, targetClass, targets);
        return targets;
    }

    private static <T> void convert(List<?> sources, Class<T> targetClass, List<T> targets) {
        if (sources == null || targets == null) {
            return;
        }
        targets.clear();
        for (Object source : sources) {
            try {
                T t = targetClass.newInstance();
                BeanUtils.copyProperties(source,t);
                targets.add(t);
            } catch (InstantiationException | IllegalAccessException e) {
                e.printStackTrace();
                return;
            }

        }
    }

}

